package com.exercise.AndroidCamera;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;
/*
기능 : 그룹관리
작성 : 하드캔
완료일 : 2014.09.26 
	*/
public class ManageGroupActivity extends BaseActivity implements OnClickListener{

	Intent mIntent;
	String userID;
	
	int numberOfBoard=6, i;
	LinearLayout linLayout;
	LinearLayout LL=null;
	int[] imgResource;

//	private ListView list;
	ArrayList<String> groupIdArray;
	ArrayList<String> groupNameArray;
	Button[] groupButton;

	Button addGroup;
	
	Button groupName;
	
	LinearLayout buttongrouplayout;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_manage_group);
		
		groupIdArray = new ArrayList<String>();
		groupNameArray = new ArrayList<String>();
		
		userID = getIntent().getExtras().getString("userID");
		linLayout = (LinearLayout) findViewById(R.id.container);
		
		getActionBar().setTitle("Post Memories");
		getActionBar().setDisplayShowHomeEnabled(false);
		
		addGroup = (Button) findViewById(R.id.createGroup);
		buttongrouplayout = (LinearLayout)findViewById(R.id.buttongrouplayout);
		
		
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		GroupListAsync GroupList = new GroupListAsync();
		GroupList.execute();
	}
	
	//comment
	protected String[] Group_list_read(Context context, String location_id){
		String pString = null;
		HttpURLConnection conn = null;
		BufferedReader br = null;
		
		String[] result = new String[2];
		result[0] = "error"; //JSON flag
		result[1] = null; //message
		
		try{
       	StringBuilder builder = new StringBuilder();
       	
       	URL url = new URL("http://54.199.194.197/mylist_group.php");
       	conn = (HttpURLConnection)url.openConnection();
       	
       	if(conn != null){
       		conn.setConnectTimeout(150000);	
       		conn.setReadTimeout(150000);
       		conn.setDefaultUseCaches(false); 
           	conn.setDoInput(true); 
           	conn.setDoOutput(true);
           	conn.setRequestMethod("POST");
           	conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
              
         	StringBuffer buffer = new StringBuffer();
         	buffer.append("user_id").append("=").append(userID);
         	Log.d("user_id_comment", buffer.toString());

            OutputStreamWriter outStream = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            PrintWriter writer = new PrintWriter(outStream);
            writer.write(buffer.toString());
            writer.flush();
            
            InputStreamReader inputStream = new InputStreamReader(conn.getInputStream(), "UTF-8"); 
            br = new BufferedReader(inputStream);
              
           	String line;
           	while((line = br.readLine()) != null){
           	   builder.append(line);
           	}
              
           	br.close();
           	
           	pString =  builder.toString();
           	
           	JSONObject jObject = new JSONObject(pString);
           	JSONArray GroupIdObject = new JSONArray(jObject.getString("group_id"));
           	JSONArray GroupNameObject = new JSONArray(jObject.getString("group_name"));
           	
           	for(int i=0; i<GroupIdObject.length(); i++){
           		groupIdArray.add(GroupIdObject.getString(i));
           		groupNameArray.add(GroupNameObject.getString(i));
           	}
           	
       	}else{
       		
       		throw new Exception("network error");
       	}
       	
       }catch(SocketTimeoutException se){
       	
       	result[1] = "network error";
       	
       }catch(Exception e){
       	
       	result[1] = e.getMessage();
       	
       }finally{
       	
       	if(conn != null)
       		conn.disconnect();

       	if(br != null){
       		try {
       			br.close();
				} catch (Exception e2) {
					// TODO: handle exception
					result[1] = e2.getMessage();
				}
       	}
       }
       return result;
	}
	
	public class GroupListAsync extends AsyncTask<String, String, String> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected String doInBackground(String... params) {
			Group_list_read(ManageGroupActivity.this, "0");
			return null;
		}
		@Override
		protected void onPostExecute(String result) {
			
//			GroupListAdapter adapter = new GroupListAdapter(ManageGroupActivity.this, R.layout.group_list, groupIdArray, groupNameArray, groupIdArray.size(), userID);
			

			groupButton = new Button[groupIdArray.size()];
			Typeface tf = Typeface.createFromAsset(ManageGroupActivity.this.getAssets(), "fonts/whitechok.ttf");
			for(int i=0; i<groupIdArray.size(); i++){
				groupName = new Button(ManageGroupActivity.this);
				groupName.setLayoutParams(new LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
				groupName.setText(groupNameArray.get(i));
				groupName.setTag(i);
				groupButton[i] = groupName;
				groupButton[i].setTextColor(0xFFFF6E57);
				groupButton[i].setTypeface(tf);
				groupButton[i].setTextSize(20);
				groupButton[i].setBackgroundResource(R.drawable.round_background_reverse);
				groupButton[i].setOnClickListener(ManageGroupActivity.this);
				buttongrouplayout.addView(groupName);
			}
			
			
			addGroup.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
			    	mIntent = new Intent(ManageGroupActivity.this, CreateGroupActivity.class);
			        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			    	mIntent.putExtra("userID", userID);
		    		startActivity(mIntent);
				}
			});
			
			super.onPostExecute(result);
		}
		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	     
	    switch(item.getItemId()){
	    
	    case android.R.id.home:
            onBackPressed();
            break;

	    default:
	        return false;
	    }
	    return true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		
		Button newButton = (Button) v;
		for(Button tempButton : groupButton)
		{
			if(tempButton == newButton)
			{
				int position = (Integer)v.getTag();
		    	mIntent = new Intent(ManageGroupActivity.this, GroupInfoActivity.class);
		        mIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		        mIntent.putExtra("groupID", groupIdArray.get(position));
		    	mIntent.putExtra("userID", userID);
	    		startActivity(mIntent);						
			}
		}
	}
}
